from gi.repository import Gtk

import os

template_menu = []

def menu():
    #print('local menu')
    global template_menu
    tempate_menu = [
        ('python','enterln:python','title:Python'),
    ]

# 终端的右键菜单
class ContextMenu: 

    def __init__(self,parent_menu_item, term): 
        self.parent_menu_item = parent_menu_item
        self.term = term
        if parent_menu_item:
            self.load_menu()
            self.add_menus(parent_menu_item, template_menu)

    def load_menu(self):
        # 如果有本地配置文件， 就优先加载
        cfg_file = '{}/.config/jingterm/templates.py'.format(os.getenv('HOME'))
        if os.path.isfile(cfg_file):
            exec(open(cfg_file, 'r').read())
        else:
            menu()

    def add_menus(self, parent, config_list):
        a = 0x40
        for c in config_list:
            a = a+1
            self.add_menu(parent, c, a)

    def add_menu(self, parent, config, mnemonic):
        name = config[0]
        mnemonic = chr(mnemonic)
        t = type(config[1])

        # 名字以！开头的为批量模式
        if name.startswith('!'):
            name = name[1:]
            menu = Gtk.MenuItem.new_with_mnemonic('_' + mnemonic + ': ' + name)
            menu.label = name
            menu.batch_mode = True
            menu.contents = config[1]
            menu.connect("activate", self.menu_clicked)
            parent.add(menu)
        elif t==str:
            menu = Gtk.MenuItem.new_with_mnemonic('_' + mnemonic + ': ' + name)
            menu.label = name
            menu.batch_mode = False
            menu.contents = config[1:]
            menu.connect("activate", self.menu_clicked)
            parent.add(menu)
        elif t==list:
            menu = Gtk.MenuItem.new_with_mnemonic('_' + mnemonic + ': ' + name)
            parent.add(menu)
            sub_list = Gtk.Menu()
            menu.set_submenu(sub_list)
            self.add_menus(sub_list, config[1])

    def menu_clicked(self, menuitem):
        if menuitem.batch_mode:
            self.term.notebook.batch_new_term(menuitem.contents)
        else:
            self.term.start_commands_thread(menuitem.contents)
